#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include <linux/stat.h>
#include <iostream>

#define FIFO_FILE       "CG_PIPE"

using namespace std;

char readbuf[128];
int fd;
int count = 0;

int read_stream(void) {
    string tmp;
    memset(readbuf, 0, sizeof(readbuf));
    //while(read(fd,readbuf,2048)!=0) {
    if(read(fd,readbuf,128)<1) {
        return 0;
    } else {
        printf("%s %d\n",readbuf,count);
        count++;
        return 1;
    }
        //tmp.append(readbuf);
        //memset(readbuf, 0, sizeof(readbuf));
    //}
    //if (tmp.size()!=0)
    //    printf("%s",tmp.data());
}

int main(void)
{
        FILE *fp;
        //char readbuf[128];
        //int fd;

        /* Create the FIFO if it does not exist */
        umask(0);
        //mknod(FIFO_FILE, S_IFIFO|0666, 0);
        mkfifo(FIFO_FILE, 0666);

        fd = open(FIFO_FILE,O_RDONLY|O_NONBLOCK);
        //fd = open(FIFO_FILE,O_RDONLY);
        //memset(readbuf, 0, sizeof(readbuf));
        while(1)
        {
                read_stream();
                //fp = fopen(FIFO_FILE, "r");
                //fd = open(FIFO_FILE,O_RDONLY|O_NONBLOCK);
                //fd = open(FIFO_FILE,O_RDONLY);
                //fgets(readbuf, 128, fp);
                //read(fd,readbuf,128);
                //string tmp(readbuf);

                //if (tmp.size()!=0) {
                //    printf("%s", tmp.data());
                //    memset(readbuf, 0, sizeof(readbuf));
                //}
                //fclose(fp);
                //close(fd);
        }
        close(fd);
        
        return(0);
}
